﻿using UnityEngine;
using System.Collections;

public class CFS_CameraControl : MonoBehaviour 
{
	[SerializeField] Transform rifle = null;
	
	[SerializeField] float cameraMinLimit = 2f;
    [SerializeField] float cameraMaxLimit = 80f;
	
	[SerializeField] float rifleMinLimit = 2f;
    [SerializeField] float rifleMaxLimit = 80f;
	
	
	[SerializeField] Transform target = null;
    [SerializeField] float distance = 10.0f;
    [SerializeField] float ySpeed = 120.0f;
	
	private float y = 0.0f;
	
	private float rotationY = 0.0f;
	
	[SerializeField] float distanceMin = 1f;
    [SerializeField] float distanceMax = 15f;
	
	
	[SerializeField] float CameraSpeed = 10f;
	
//	void Start()
//	{
		
//	}
 
    void LateUpdate ()
	{
		MoveCamera();
		MoveRifle();
    }
	
	void MoveCamera()
	{
		//calculate camera Rotation
		if(Input.GetMouseButton(1))
		{
	        rotationY -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
	        rotationY = ClampAngle(rotationY, cameraMinLimit, cameraMaxLimit);
		}
		
        Quaternion newRotation = Quaternion.Euler(rotationY, 0f, 0f);
		
        distance = ZDistance();
		
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
		Vector3 newPosition = newRotation * negDistance + target.localPosition;
		
		//apply new rotations
    	transform.localRotation = Quaternion.Lerp(transform.localRotation, newRotation, Timing.CustomDeltaTime() * CameraSpeed);
		transform.localPosition = Vector3.Lerp(transform.localPosition, newPosition, Timing.CustomDeltaTime() * CameraSpeed);
	}
	
	void MoveRifle()
	{
		//calculate rifle rotation
		y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
		y = ClampAngle(y, rifleMinLimit, rifleMaxLimit);
		
        Vector3 rifleRotation = Vector3.right * y;
		rifle.localRotation = Quaternion.Euler(rifleRotation);
	}
	
	public float ZDistance()
	{
		return Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);
	}
		
    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}